package org.mg.frontend.bean;

import org.mg.core.entity.Role;
import org.mg.core.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.Serializable;

/**
 * @author MG
 */
@ManagedBean(name = "sessionState")
@SessionScoped
public class SessionStateBean implements Serializable{
    private static final Logger logger = LoggerFactory.getLogger(SessionStateBean.class);

    private static final String USER_HOME = "/view/page.xhtml";
    private static final String ADMIN_HOME = "/view/admin/page.xhtml";

    public static final String ROLE_ADMIN = "ROLE_ADMIN";

    User authenticatedUser;

    public void doRedirect() {
        String redirectPage = USER_HOME;

        if (userHasRole(ROLE_ADMIN)) {
            redirectPage = ADMIN_HOME;
        }

        try {
            HttpServletRequest request = (HttpServletRequest) BeanUtils.getExternalContext().getRequest();
            BeanUtils.getExternalContext().redirect(request.getContextPath() + redirectPage);
        } catch (IOException e) {
            logger.error("Redirect error: ", e);
        }
    }

    public boolean userHasRole(String userRole) {
        if (authenticatedUser != null) {
            for (Role role : authenticatedUser.getRoles()) {
                if (role.getRole().equals(userRole)) {
                    return true;
                }
            }
        }

        return false;
    }

    public User getAuthenticatedUser() {
        return authenticatedUser;
    }

    public void setAuthenticatedUser(User authenticatedUser) {
        this.authenticatedUser = authenticatedUser;
    }
}
